package com.ruoyi.system.commons.utils;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.IdUtil;
import com.ruoyi.common.utils.SecurityUtils;

import lombok.extern.slf4j.Slf4j;

import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;

/**
 * @Auther Yulong Liu
 * @Date 2023/12/13 15:51
 * @Description 雪花算法，生成唯一的内容
 **/

@Slf4j
@Component
public class IdGeneratorSnowflake {
    private long workerId = 0;  //id前面的部分
    private long datacenterId = 1;  //id后面的部分
    private Snowflake snowflake = IdUtil.createSnowflake(workerId, datacenterId);


    @PostConstruct  //构造后开始执行，加载初始化工作
    public void init(){
        try{
            //获取本机的ip地址编码
            workerId = NetUtil.ipv4ToLong(NetUtil.getLocalhostStr());
            log.info("当前机器的workerId: " + workerId);
        }catch (Exception e){
            e.printStackTrace();
            log.warn("当前机器的workerId获取失败 ----> " + e);
            workerId = NetUtil.getLocalhostStr().hashCode();
        }
    }

    public synchronized long snowflakeId() {
        return snowflake.nextId();
    }

    public synchronized long snowflakeId(long workerId, long datacenterId) {
        Snowflake snowflake = IdUtil.createSnowflake(this.workerId, this.datacenterId);
        return snowflake.nextId();
    }
}